import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'
import img from '../../components/images/avatar.png'

const foodStore = createSlice({
    name: 'foods',
    initialState: {
        foodsList: [],
        activeIndex: 0,
        cartList: []
    },
    reducers: {
        setFoodList(state, action) {
            state.foodsList = action.payload
        },
        setactiveIndex(state, action) {
            state.activeIndex = action.payload
        },
        setCartList(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item){
                item.count++
                console.log(item.count)
            }
            else {
                state.cartList.push(action.payload)
            }
        },
        increby(state,action){
             const item = state.cartList.find(item => item.id == action.payload)
             item.count++
        },
        decreby(state,action){
            const item = state.cartList.find(item => item.id == action.payload)
            if (item.count == 0)
                return
            item.count --
        },
        clearCartlist(state,action){
            state.cartList = []
        }
    }
})

const { setFoodList, setactiveIndex,setCartList,increby ,decreby,clearCartlist} = foodStore.actions

//异步获取数据部分
const feachFoodList = () => {
    return async (dispatch) => {
        const res = await axios.get('http://localhost:3004/takeaway')
        dispatch(setFoodList(res.data))
    }
}

const foodReducer = foodStore.reducer

export default foodReducer
export { feachFoodList, setactiveIndex ,setCartList,increby ,decreby,clearCartlist}
